package com.shouer.doc.ui.splash.presenter;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.ApkUtil;
import com.shouer.doc.common.util.FileUtil;
import com.shouer.doc.common.util.SdCardUtils;
import com.shouer.doc.common.util.Tools;
import com.shouer.doc.event.LoginToRongEvent;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.service.UploadService;
import com.shouer.doc.ui.login.model.DoctorInfoModel;
import com.shouer.doc.ui.login.model.UserModel;
import com.shouer.doc.ui.login.response.LoginResponse;
import com.shouer.doc.ui.splash.response.VersionUpdateResponse;
import com.shouer.doc.ui.splash.view.ISplashView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

/**
 * Created by ZXL on 2016/12/15.
 */

public class SplashPresenterCompl implements ISplashPresenter {

    private ISplashView splashView;
    private UserModel userModel;
    private DoctorInfoModel doctorInfoModel;

    public SplashPresenterCompl(ISplashView splashView) {
        this.splashView = splashView;
        EventBus.getDefault().register(this);
    }

    @Override
    public void checkVersion(String currentVersion) {

        Map<String, String> param = new HashMap<>();
        param.put("os","0");
        param.put("currentVersion",currentVersion);
        param.put("flag","1");
        final GsonRequest<VersionUpdateResponse> request = new GsonRequest(ShouerConst.APP_SERVER,"versionUpdate", VersionUpdateResponse.class, new Response.Listener<VersionUpdateResponse>() {
            @Override
            public void onResponse(VersionUpdateResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                splashView.checkVersionFailed();
            }
        });

        RequestUtil.sendRequest(splashView.getContext(), param, request);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(VersionUpdateResponse response)
    {
        if (response.getErrorCode()>=0)
        {
            splashView.checkVersionSuccess(response);
        }else
        {
            splashView.checkVersionFailed();
        }

    }

    @Override
    public void autoLogin(String userName, String password) {

        Map<String, String> param = new HashMap<>();
        param.put("userPhone", userName);
        param.put("password", password);
        param.put("uuid",  Tools.getUUID(splashView.getContext()));

        final GsonRequest<LoginResponse> request = new GsonRequest("docLogin", LoginResponse.class, new Response.Listener<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                splashView.autoLoginFailed();
            }
        });

        RequestUtil.sendRequest(splashView.getContext(), param, request);


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginResponse loginResponse)
    {
        if (loginResponse.getErrorCode()>=0)
        {
            loginResponse.getUser().setRongToken(loginResponse.getToken());
            userModel=loginResponse.getUser();
            doctorInfoModel=loginResponse.getDoctor();
            loginToRongCloud(userModel.getRongToken());
        }else
        {
            splashView.autoLoginFailed();
        }
    }

    private void loginToRongCloud(String rongToken) {

        RongIM.connect(rongToken, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Log.e(ISplashPresenter.class.getSimpleName(),"onTokenIncorrect()");
                EventBus.getDefault().post(new LoginToRongEvent(false));

            }

            @Override
            public void onSuccess(String s) {
                Log.d(ISplashPresenter.class.getSimpleName(),"onSuccess:"+s);
                EventBus.getDefault().post(new LoginToRongEvent(true));
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

                Log.d(ISplashPresenter.class.getSimpleName(), "--onError" + errorCode);
                if (errorCode != RongIMClient.ErrorCode.RC_CONN_OVERFREQUENCY) {
                    EventBus.getDefault().post(new LoginToRongEvent(false));
                } else {
                    EventBus.getDefault().post(new LoginToRongEvent(true));
                }

            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginToRongEvent event)
    {
        if (event.isSuccess())
        {
            RongIM.getInstance().setCurrentUserInfo(new UserInfo(doctorInfoModel.getDocId(),
                    doctorInfoModel.getDocName(),
                    Uri.parse(FileUtil.connectFilePath(ShouerConst.RES_SERVER,doctorInfoModel.getDocImageUrl()))));
            RongIM.getInstance().setMessageAttachedUserInfo(true);
            splashView.getApp().setUserModel(userModel);
            splashView.getApp().setUserDocInfo(doctorInfoModel);
            splashView.autoLoginSuccess();
        }else
        {
            splashView.autoLoginFailed();
        }
    }


    @Override
    public void uploadApplication(VersionUpdateResponse versionInfo) {


        String apkSdPath = FileUtil.connectFilePath(ShouerConst.APK_DOWNLOAD_PATH, versionInfo.getAppFileName());
        File apkFile = new File(FileUtil.connectFilePath(SdCardUtils.getSDCardPath(), apkSdPath));

        if (apkFile.exists()) {
            boolean isOk = ApkUtil.checkApkFile(splashView.getContext(), apkFile.getAbsolutePath());
            if (isOk) {
                ApkUtil.install(splashView.getContext(), apkFile);
            } else {
                Intent intent = new Intent();
                intent.setAction("shouer_doc_update");
                intent.setPackage(splashView.getContext().getPackageName());
                intent.putExtra("versionInfo", versionInfo);
                splashView.getContext().bindService(intent, connection, splashView.getContext().BIND_AUTO_CREATE);
            }
        } else {
            Intent intent = new Intent();
            intent.setAction("shouer_doc_update");
            intent.setPackage(splashView.getContext().getPackageName());
            intent.putExtra("versionInfo", versionInfo);
            splashView.getContext().bindService(intent, connection, splashView.getContext().BIND_AUTO_CREATE);
        }

    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            ((UploadService.DownLoadManager) service).startDownLoadApk();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //Do NoThing
        }
    };

    @Override
    public void onDestroy() {

        EventBus.getDefault().unregister(this);
        splashView=null;
    }
}
